/////////////////////////////////////////////////////////
//                                                     //
// Copyright (c) 2016年 上证云平台. All rights reserved. //
//                                                     //
/////////////////////////////////////////////////////////

#import "OHLCViewController.h"

#if __has_include("MChartView.h")

#import "MChartView.h"
#import "MApi.h"

#define MPlotGenerate(class, yAxis) [[class alloc] initWithYAxisLabelCount:yAxis]

@interface OHLCViewController () <UIActionSheetDelegate, UIAlertViewDelegate>
@property (nonatomic, strong) UISegmentedControl *seg;
@property (nonatomic, strong) MOHLCChartView *chartView;
@property (nonatomic, strong) NSArray *majorPlots;
@property (nonatomic, strong) NSArray *minorPlots;
@property (nonatomic, weak) NSTimer *timer;
@end

@implementation OHLCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"日", @"周", @"月", @"15分", @"30分", @"60分"]];
    self.seg.selectedSegmentIndex = 0;
    [self.seg addTarget:self action:@selector(segChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.seg];
    
    self.chartView = [[MOHLCChartView alloc] initWithFrame:CGRectMake(5, 5, CGRectGetWidth(self.view.frame) - 10, 300)];
    self.chartView.code = @"000952.csi";
    
    MOHLCChartTheme *theme = [MChartTheme defaultTheme];
    theme.longitudinalLatitude = MOHLCChartLongitudinalLatitudeThreeMonth;
    theme.xAxisTextLocation = MOHLCChartXAxisTextLocationCenter;
    theme.numberOfMinimumVisibleRecords = 10;
    theme.numberOfVisibleRecords = 50;
    self.chartView.theme = theme;
    
    
//    self.chartView.backgroundColor = [UIColor orangeColor];
//    self.chartView.borderWidth = 5;
//    self.chartView.borderColor = [UIColor brownColor];
//    self.chartView.insideLineColor = [UIColor purpleColor];
//    self.chartView.insideLineWidth = 3;
//    self.chartView.yAxisFont = [UIFont boldSystemFontOfSize:25.0];
//    self.chartView.yAxisTextColor = [UIColor blueColor];
//    self.chartView.xAxisFont = [UIFont boldSystemFontOfSize:25];
//    self.chartView.xAxisTextColor = [UIColor redColor];
//    self.chartView.enquiryFrameColor = [UIColor blueColor];
//    self.chartView.enquiryLineColor = [UIColor orangeColor];
//    self.chartView.enquiryTextColor = [UIColor yellowColor];
//    self.chartView.enquiryTextFont = [UIFont boldSystemFontOfSize:17];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(0, 0, 60, 20);
    button.backgroundColor = [UIColor blueColor];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitle:@"设均线" forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(MASettingButtonClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(0, 0, 60, 20);
    button1.backgroundColor = [UIColor yellowColor];
    [button1 setTitle:@"主图" forState:UIControlStateNormal];
    [button1 addTarget:self
               action:@selector(majorPlotChangeIndexButtonClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button3.frame = CGRectMake(0, 0, 60, 20);
    button3.backgroundColor = [UIColor yellowColor];
    [button3 setTitle:@"不复权" forState:UIControlStateNormal];
    [button3 addTarget:self
                action:@selector(priceModeButtonClicked:)
      forControlEvents:UIControlEventTouchUpInside];
    self.chartView.majorPlotLeftButtons = @[button1,button,button3];
    
    
    UIButton * button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.frame = CGRectMake(0, 0, 50, 20);
    button2.backgroundColor = [UIColor yellowColor];
    [button2 setTitle:@"副指标" forState:UIControlStateNormal];
    [button2 addTarget:self
               action:@selector(minorPlotChangeIndexButtonClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    self.chartView.minorPlotLeftButtons = @[button2];
    
    MMAPlot *ploot = MPlotGenerate(MMAPlot, 5);
//    ploot.options = @{@"Y_AXIS_LABELS_HIDDEN" : @[@NO, @YES, @NO, @YES, @NO]};
    [ploot setParameters:5, 10, 15, 20, nil];
    [ploot setLineColors:[UIColor whiteColor],
     [UIColor yellowColor],
     [UIColor greenColor],
     [UIColor orangeColor],
     [UIColor purpleColor],
     [UIColor brownColor],
     [UIColor cyanColor], nil];
    ploot.type = MOHLCChartTypeDay;
    ploot.barFill = YES;
    
    self.majorPlots = @[ploot, MPlotGenerate(MBOLLPlot, 5)];
    
    self.chartView.majorPlots = self.majorPlots;
    
    
    MVOLPlot *volPloot = MPlotGenerate(MVOLPlot, 3);
    [volPloot setParameters:10,50,nil];
    
    
    self.minorPlots = @[volPloot,
                        MPlotGenerate(MKDPlot, 3),
                        MPlotGenerate(MMACDPlot, 3),
                        MPlotGenerate(MRSIPlot, 3),
                        MPlotGenerate(MDMIPlot, 3),
                        MPlotGenerate(MKDJPlot, 3),
                        MPlotGenerate(MBIASPlot, 3),
                        MPlotGenerate(MOBVPlot, 3),
                        MPlotGenerate(MBBIPlot, 3),
                        MPlotGenerate(MCCIPlot, 3),
                        MPlotGenerate(MMTMPlot, 3),
                        MPlotGenerate(MROCPlot, 3),
                        MPlotGenerate(MARPlot, 3),
                        MPlotGenerate(MBRPlot, 3),
                        MPlotGenerate(MVRPlot, 3),
                        MPlotGenerate(MNVIPlot, 3),
                        MPlotGenerate(MPVIPlot, 3),
                        MPlotGenerate(MWRPlot, 3),
                        MPlotGenerate(MPSYPlot, 3)
                        ];
    self.chartView.minorPlots = self.minorPlots;
    
    
    [self.view addSubview:self.chartView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startEnquiry:) name:MChartDidStartEnquiryNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEnquiry:) name:MChartDidEndEnquiryNotification object:nil];

    
    
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.seg.frame = CGRectMake(5, 5, CGRectGetWidth(self.view.frame) - 10, 30);
    self.chartView.frame = CGRectMake(5, CGRectGetMaxY(self.seg.frame) + 5, CGRectGetWidth(self.view.frame) - 10, MIN(300, CGRectGetHeight(self.view.frame) - CGRectGetMaxY(self.seg.frame) - 5));
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(fetch) userInfo:nil repeats:YES];
    [self.timer fire];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.timer invalidate];
}


#pragma mark - private

- (void)fetch {
    [self.chartView reloadData];
}

#pragma mark - event
- (void)segChanged:(UISegmentedControl *)seg {
    
    [self.chartView.majorPlots enumerateObjectsUsingBlock:^(MMAPlot *plot, NSUInteger idx, BOOL * _Nonnull stop) {
        plot.type = seg.selectedSegmentIndex;
    }];
    
    switch (seg.selectedSegmentIndex) {
        case MOHLCChartTypeDay:
        {
            ((MOHLCChartTheme *)self.chartView.theme).longitudinalLatitude = MOHLCChartLongitudinalLatitudeNone;
            break;
        }
        case MOHLCChartTypeWeek:
        {
            ((MOHLCChartTheme *)self.chartView.theme).longitudinalLatitude = MOHLCChartLongitudinalLatitudeThreeMonth;
            break;
        }
        case MOHLCChartTypeMonth:
        {
            ((MOHLCChartTheme *)self.chartView.theme).longitudinalLatitude = MOHLCChartLongitudinalLatitudeOneYear;
            break;
        }
        default:
        {
            ((MOHLCChartTheme *)self.chartView.theme).longitudinalLatitude = MOHLCChartLongitudinalLatitudeNone;
            break;
        }
    }
    
    
    
//    [self.chartView reloadData];
}
- (void)priceModeButtonClicked:(UIButton *)button {
    UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"设置复权" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"不复权",@"前复权",@"后复权",nil];
    as.tag = 'fq';
    [as showInView:self.view];
}

- (void)MASettingButtonClicked:(UIButton *)button {
    NSString *message = nil;
    NSInteger t = 'ot';
    if (self.chartView.majorPlotIndex == 0) {
        message = @"以逗点隔开, 如:2,3,4,5,6";
        t = 'ma';
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"设均线" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    alertView.tag = t;
    alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alertView show];
}

- (void)majorPlotChangeIndexButtonClicked:(UIButton *)button {
    UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"选主图" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    as.tag = 'mj';
    [self.majorPlots enumerateObjectsUsingBlock:^(MPlot *plot, NSUInteger idx, BOOL * _Nonnull stop) {
        [as addButtonWithTitle:plot.title];
    }];
    [as showInView:self.view];
}

- (void)minorPlotChangeIndexButtonClicked:(UIButton *)button {
    UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"选副指标" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    as.tag = 'mi';
    [self.minorPlots enumerateObjectsUsingBlock:^(MPlot *plot, NSUInteger idx, BOOL * _Nonnull stop) {
        [as addButtonWithTitle:plot.title];
    }];
    [as showInView:self.view];
}

- (void)startEnquiry:(NSNotification *)notification {
    MOHLCItem *item = notification.object;
    NSString *string = [NSString stringWithFormat:@"%@:%@:%@:%@:%@",
                        item.openPrice,
                        item.closePrice,
                        item.amount,
                        item.tradeVolume?:@"-",
                        item.datetime];
    self.navigationItem.title = string;
}

- (void)endEnquiry:(NSNotification *)notification {
    self.navigationItem.title = nil;
}


#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 'mj') {
        self.chartView.majorPlotIndex = buttonIndex - 1;
        MPlot *plot = self.chartView.majorPlots[buttonIndex - 1];
        UIButton *but = self.chartView.majorPlotLeftButtons[0];
        [but setTitle:plot.title forState:UIControlStateNormal];
    }else if (actionSheet.tag == 'fq') {
        
        const NSArray *titles = @[@"不复权",@"前复权",@"后复权"];
        [self.chartView.majorPlots enumerateObjectsUsingBlock:^(MMAPlot *plot, NSUInteger idx, BOOL * _Nonnull stop) {
            plot.priceAdjustedMode = buttonIndex;
        }];
        UIButton *but = self.chartView.majorPlotLeftButtons[2];
        [but setTitle:titles[buttonIndex] forState:UIControlStateNormal];
        
    } else {
        self.chartView.minorPlotIndex = buttonIndex - 1;
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        return;
    }
    UITextField *tf = [alertView textFieldAtIndex:0];
    MMAPlot *plot = nil;
    if (alertView.tag == 'ma') {
        plot = self.majorPlots[0];
        NSArray *component = [tf.text componentsSeparatedByString:@","];
        [plot setParametersFromArray:component];
    } else {
        plot = self.majorPlots[1];
        [plot setParameters:tf.text.integerValue, 2, nil];
    }
    [plot redraw];
}

@end

#endif
